#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import argparse
import subprocess
import logging
from pathlib import Path

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    handlers=[
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("start_webrtc")

# 当前目录
BASE_DIR = Path(os.path.dirname(os.path.abspath(__file__)))

def check_dependencies():
    """检查依赖项"""
    required_packages = [
        "aiohttp",
        "aiortc",
        "opencv-python",
        "numpy",
        "aiohttp_cors"
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace("-", "_"))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        logger.warning(f"缺少以下依赖项: {', '.join(missing_packages)}")
        logger.info("正在安装缺失的依赖项...")
        
        try:
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", 
                *missing_packages
            ])
            logger.info("依赖项安装完成")
        except subprocess.CalledProcessError as e:
            logger.error(f"安装依赖项失败: {e}")
            logger.info("请手动安装以下依赖项:")
            logger.info(f"pip install {' '.join(missing_packages)}")
            return False
    
    # 检查可选的cairosvg依赖
    try:
        __import__("cairosvg")
    except ImportError:
        logger.warning("未安装cairosvg，SVG图像将使用占位符替代")
        logger.info("如需支持SVG图像，请安装: pip install cairosvg")
    
    return True

def start_server(host, port, verbose):
    """启动WebRTC服务器"""
    server_script = BASE_DIR / "webrtc_server.py"
    
    if not server_script.exists():
        logger.error(f"服务器脚本不存在: {server_script}")
        return False
    
    # 确保脚本可执行
    os.chmod(server_script, 0o755)
    
    # 构建命令
    cmd = [sys.executable, str(server_script), "--host", host, "--port", str(port)]
    
    if verbose:
        cmd.append("--verbose")
    
    try:
        logger.info(f"启动WebRTC远程桌面服务器 http://{host}:{port}")
        process = subprocess.Popen(cmd)
        
        logger.info("服务器已启动，按Ctrl+C停止")
        process.wait()
        
    except KeyboardInterrupt:
        logger.info("正在停止服务器...")
        process.terminate()
        process.wait()
        logger.info("服务器已停止")
    except Exception as e:
        logger.error(f"启动服务器失败: {e}")
        return False
    
    return True

def main():
    parser = argparse.ArgumentParser(description="启动WebRTC远程桌面服务器")
    parser.add_argument("--host", default="0.0.0.0", help="监听主机")
    parser.add_argument("--port", type=int, default=8080, help="监听端口")
    parser.add_argument("--verbose", action="store_true", help="启用详细日志")
    parser.add_argument("--skip-deps-check", action="store_true", help="跳过依赖检查")
    
    args = parser.parse_args()
    
    # 检查依赖项
    if not args.skip_deps_check:
        if not check_dependencies():
            return 1
    
    # 启动服务器
    if not start_server(args.host, args.port, args.verbose):
        return 1
    
    return 0

if __name__ == "__main__":
    sys.exit(main())